package com.app.backend.password.check.config;

import com.app.backend.password.check.aop.DecryptType;
import com.app.backend.password.check.service.DecryptServiceContext;
import com.app.backend.common.utils.ClassScanner;
import com.google.common.collect.Maps;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author Jet Zheng
 */
@Component
@SuppressWarnings("unchecked")
public class DecryptServiceProcessor implements BeanFactoryPostProcessor {

    private static final String HANDLER_PACKAGE = "com.**.password.check.service";

    /**
     * 扫描@EncryptType，初始化HandlerContext，将其注册到spring容器
     *
     * @param beanFactory
     * @throws BeansException
     */
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        Map<String, Class> handlerMap = Maps.newHashMapWithExpectedSize(3);

        //加载默认Service
        ClassScanner.scan(HANDLER_PACKAGE, DecryptType.class).forEach(clazz -> {
            String name = clazz.getAnnotation(DecryptType.class).name();
            handlerMap.put(name, clazz);
        });

        // 初始化BenefitServiceContext，将其注册到spring容器中
        DecryptServiceContext context = new DecryptServiceContext(handlerMap);
        beanFactory.registerSingleton(DecryptServiceContext.class.getName(), context);
    }
}